﻿using AutoMapper;
using Basic.Traceability.Domain.Freed;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Write.Application.Command.Freed.HealthInformation;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;
using Yitter.IdGenerator;

namespace Basic.Traceability.Host.Api.Write.Application.Handler.Freed.HealthInformation
{
    public class CreateHealthInformationHandler : IRequestHandler<CreateHealthInformationCommand, APIResult<int>>
    {
        private readonly IBaseRepository<HealthInformationModel> healthRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CreateHealthInformationHandler> logger;

        public CreateHealthInformationHandler(IBaseRepository<HealthInformationModel> healthRepository, IMapper mapper, ILogger<CreateHealthInformationHandler> logger)
        {
            this.healthRepository = healthRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 添加免疫信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateHealthInformationCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = mapper.Map<HealthInformationModel>(request);
            model.Id = YitIdHelper.NextId();
            var r = healthRepository.Create(model);
            if (r > 0)
            {
                res.Msg = "添加免疫信息成功";
                res.Data = r;
                res.Code = APIEnums.Success;
                logger.LogInformation("添加免疫信息成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Msg = "添加免疫信息失败";
                res.Data = r;
                res.Code = APIEnums.Fail;
                logger.LogError("添加免疫信息失败");
                return Task.FromResult(res);
            }
        }
    }
}
